package com.spider.base;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import com.spider.exception.ExecuterServiceIsNullException;
import com.spider.util.ExecuteServiceType;


public class BaseExecute {
	
	 private static final Logger log = Logger.getLogger(BaseExecute.class);
	 private static ExecutorService exc = null;
	 
	 public static void initExec(ExecuteServiceType type){
		 if(type!=null){
			switch (type) {
			 	case FIXED_THREAD_POOL:
			 		 exc = GetExecute.getFixedThreadPool();
				break;
			 	case CACHED_THREAD_POOL:
			 		 exc = GetExecute.getCachedThreadPool();
			 		break;
			 	case SINGLE_THREAD_POOL:
			 		 exc = GetExecute.getSingleThreadPool();
			 		break;
			 	case SCHEDULE_THREAD_POOL:
			 		 exc = GetExecute.getScheduleThreadpool();
			 		break;
				default:
					 exc = GetExecute.getCachedThreadPool();
					break;
			}
		 }else{
			 exc = GetExecute.getCachedThreadPool();
		 }
	 }
	 
	 
	/*** 执行定时任务
	 * @param task
	 * @throws ExecuterServiceIsNullException 
	 * @throws Exception 
	 */
	public static <T> Future<T> ExecuteOne(BaseTask<T> task,ExecuteServiceType type) throws ExecuterServiceIsNullException {
		Future<T> result = null;
		if(checkExecuter(type)){
			result = exc.submit(task);
		}		
		return result;
	}
	
	/*** 批量执行任务
	 * @param task
	 * @throws InterruptedException 
	 * @throws ExecuterServiceIsNullException 
	 * @throws Exception 
	 */
	public static <T> List<Future<T>> ExecuteBitch(List<BaseTask<T>> tasks,ExecuteServiceType type) throws ExecuterServiceIsNullException, InterruptedException{
		List<Future<T>> result = null;
		if(checkExecuter(type)){
			try {
				result = exc.invokeAll(tasks);
			} catch (InterruptedException e) {
				log.error("execute task error!");
				throw e;
			}
		}		
		return result;
	}
	
	/*** 批量执行任务
	 * @param <T>
	 * @param task
	 * @throws InterruptedException 
	 * @throws ExecuterServiceIsNullException 
	 * @throws Exception 
	 */
	public static <T> List<Future<T>> ExecuteBitch(List<BaseTask<T>> tasks,ExecuteServiceType type,Long timeout,TimeUnit unit) throws ExecuterServiceIsNullException, InterruptedException{
		List<Future<T>> result = null;
		if(checkExecuter(type)){
			try {
				result = exc.invokeAll(tasks, timeout, unit);
			} catch (InterruptedException e) {
				log.error("execute task error!");
				throw e;
			}
		}		
		return result;
	}
	
	/**检测 exc 是否为 null
	 * @throws Exception */
	private static boolean checkExecuter(ExecuteServiceType type) throws ExecuterServiceIsNullException{
		boolean result = false;
		if(exc!=null){
			result = true;
		}else{
			initExec(type);
		}
		
		if(!exc.isShutdown()){
			result = true;
		}else{
			log.error("executer is null!");
			throw new ExecuterServiceIsNullException();
		}
		return result;
	}
	
	
}
